export function camelToKebab (str) {
  return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()
}

export function kebabToCamel (str) {
  return str.replace(/-([a-z])/g, g => g[1].toUpperCase())
}

export function dateFormat (date, format) {
  if (!date) {
    return date
  }
  let n = new Date(date)
  var d = Date.UTC(n.getFullYear(), n.getMonth(), n.getDate(), n.getHours(), n.getMinutes(), n.getSeconds(), n.getMilliseconds())
  return new Date(d).toISOString().slice(0, 19).replace('T', ' ')
}

export function dateYMD (date) {
  if (!date) {
    return date
  }
  let d = new Date(date)
  return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()
}
export function buildUrl (url, params) {
  return url ? url.replace(/\{\{(\w+)\}\}/g, ($0, $1) => {
    return params && params.hasOwnProperty($1) ? params[$1] : ''
  }) : url
}
export function cleanHtml (content, len, ext) {
  if (!ext) {
    ext = ''
  }
  let pe = document.createElement('p')
  pe.innerHTML = content.replace(/<(?!(img|a)).*?>/g, '')
  let html = ''
  let count = 0
  let isOutLen = false
  for (let node of pe.childNodes) {
    if (node.nodeName === 'IMG') {
      if (node.dataset.face) {
        count = count + 3
        if (count <= len) {
          html = html + node.outerHTML
        } else {
          isOutLen = true
        }
      }
    } else if (node.nodeName === 'A') {
      if (node.dataset.atwhoAtQuery) {
        count = count + node.dataset.datas.length
        if (count <= len) {
          html = html + node.outerHTML
        } else {
          isOutLen = true
        }
      }
    } else if (node.nodeName === '#text') {
      let value = node.nodeValue
      if (count + value.length > len) {
        isOutLen = true
        html = html + value.substring(0, len - count)
        count = len
      } else {
        html = html + value
        count = count + value.length
      }
    }
  }
  html = convertEmoji(html)
  // html = html.replace(/\r/g, '').replace(/\n/g, '')
  return isOutLen ? html + ext : html
}
export function convertEmoji (content) {
  return content.replace(/<img.*?\s+data-face="(.*?)".*?>/g, ($0, $1) => {
    if ($1) {
      return $0.replace(/\s*src=".*?"/g, '').replace(/data-face="(.*?)"/, ($0, $1) => `${$0} src="${basePath}static/emoji/${$1}"`)
    } else {
      return $0
    }
  })
}